<template>
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
        </template>
    </BasicForm>
    <BasicTable title="题目列表" titleTooltip="关注永雏塔菲喵，关注永雏塔菲谢谢喵" :columns="columns" :request="loadDataTable"
        :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
        @update:checked-row-keys="onCheckedRow">
        <template #tableTitle>
            <n-button type="primary" @click="addTable">
                <template #icon>
                    <n-icon>
                        <PlusOutlined />
                    </n-icon>
                </template>
                新建
            </n-button>
        </template>
        <template #toolbar>
            <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </template>
    </BasicTable>
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="questionTitle"
        style="width:100%;height:100vh;" class=" overflow-scroll">
        <!-- {{ JSON.stringify(formParams) }} -->
        <!-- 单选题 -->
        <n-tabs type="segment" ref="tabsInstRef" v-model:value="tabValue" animated @update:value="handleTabUpdate">
            <n-tab-pane name="single" tab="单选题">
                <n-form label-placement="top" :label-width="80" class="py-4">
                    <n-form-item label="标题">
                        <n-input v-model:value="formParams.title" />
                    </n-form-item>
                    <n-form-item label="选项">
                        <n-dynamic-input v-model:value="formParams.options" :on-create="onCreateOption">
                            <template #create-button-default>
                                增加选项
                            </template>
                            <template #default="{ value, index }">
                                <div class=" hidden">{{ value.key = index }}</div>
                                <div style="display: flex; align-items: center; width: 100%">
                                    <n-radio :checked="formParams.answer == index" :value="index" name="basic-demo"
                                        @change="() => { formParams.answer = index }">答案</n-radio>
                                    <n-input v-model:value="value.content" type="text" />
                                </div>
                            </template>
                        </n-dynamic-input>
                    </n-form-item>
                    <n-form-item label="题目标签">
                        <n-select v-model:value="formParams.tag" filterable tag :options="tagOptions" />
                    </n-form-item>
                </n-form>
            </n-tab-pane>
            <!-- 多选题 -->
            <n-tab-pane name="multi" tab="多选题">
                <n-form label-placement="top" :label-width="80" class="py-4">
                    <n-form-item label="标题">
                        <n-input v-model:value="formParams.title" />
                    </n-form-item>
                    <n-form-item label="选项">
                        <n-dynamic-input v-model:value="formParams.options" :on-create="onCreateOption">
                            <template #create-button-default>
                                增加选项
                            </template>
                            <template #default="{ value, index }">
                                <div class=" hidden">{{ value.key = index }}</div>
                                <div style="display: flex; align-items: center; width: 100%">
                                    <n-checkbox v-model:checked="value.isAnswer" style="">答&nbsp;案&nbsp;</n-checkbox>
                                    <n-input v-model:value="value.content" type="text" />
                                </div>
                            </template>
                        </n-dynamic-input>
                    </n-form-item>
                    <n-form-item label="题目标签">
                        <n-select v-model:value="formParams.tag" filterable tag :options="tagOptions" />
                    </n-form-item>
                </n-form>
            </n-tab-pane>
            <!-- 判断题 -->
            <n-tab-pane name="judge" tab="判断题">
                <n-form-item label="标题">
                    <n-input v-model:value="formParams.title" />
                </n-form-item>
                <n-form inline>
                    <n-form-item>
                        <n-checkbox v-model:checked="formParams.answer" style="">是否正确</n-checkbox>
                    </n-form-item>
                    <n-form-item label="题目标签">
                        <n-select v-model:value="formParams.tag" filterable tag :options="tagOptions" />
                    </n-form-item>
                </n-form>
            </n-tab-pane>
            <!-- 填空题 -->
            <n-tab-pane name="blank" tab="填空题">
                <n-form-item label="标题">
                    <n-input v-model:value="formParams.title" />
                </n-form-item>
                <n-form-item label="题目内容">
                    <n-card>
                        <QuillEditor ref="quillEditor" :options="options" v-model:content="formParams.content"
                            @ready="readyQuill" style="height: 250px" class="quillEditor" />
                    </n-card>
                </n-form-item>
                <n-form-item label="正确答案">
                    <n-input v-model:value="formParams.answer" type="textarea" placeholder="基本的 Textarea" />
                </n-form-item>
                <n-form-item label="题目标签">
                    <n-select v-model:value="formParams.tag" filterable tag :options="tagOptions" />
                </n-form-item>
            </n-tab-pane>
            <!-- 简答题 -->
            <n-tab-pane name="short" tab="简答题">
                <n-form-item label="标题">
                    <n-input v-model:value="formParams.title" />
                </n-form-item>
                <n-form-item label="题目内容">
                    <n-card>
                        <QuillEditor ref="quillEditor" :options="options" v-model:content="formParams.content"
                            @ready="readyQuill" style="height: 250px" class="quillEditor" />
                    </n-card>
                </n-form-item>
                <n-form-item label="参考答案">
                    <n-input v-model:value="formParams.answer" type="textarea" placeholder="基本的 Textarea" />
                </n-form-item>
                <n-form-item label="题目标签">
                    <n-select v-model:value="formParams.tag" filterable tag :options="tagOptions" />
                </n-form-item>
            </n-tab-pane>

        </n-tabs>

        <template #action>
            <n-space>
                <n-button @click="() => (showModal = false)">取消</n-button>
                <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
            </n-space>
        </template>
    </n-modal>
</template>
<script lang="ts" setup>
import { columns } from './questionColumns';
import { getTableList, getTagList, deleteQuestion } from '@/api/teacher/question';
import { BasicTable, TableAction } from '@/components/Table';
import { PlusOutlined } from '@vicons/antd';
import { h, reactive, ref } from 'vue';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { useRoute } from 'vue-router';
import { useDialog, useMessage, TabsInst } from 'naive-ui';
import { http } from '@/utils/http/axios';
import { BasicForm, FormSchema, useForm } from '@/components/Form';

const quillEditor = ref();
const route = useRoute();
const options = reactive({
    modules: {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // toggled buttons
            ['blockquote', 'code-block'],

            [{ header: 1 }, { header: 2 }], // custom button values
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
            [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
            [{ direction: 'rtl' }], // text direction

            [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
            [{ header: [1, 2, 3, 4, 5, 6, false] }],

            [{ color: [] }, { background: [] }], // dropdown with defaults from theme
            [{ font: [] }],
            [{ align: [] }],
            ['clean'],
            ['image'],
        ],
    },
    theme: 'snow',
    placeholder: '输入您喜欢的内容吧！',
});
const tabValue = ref('single')
const tabsInstRef = ref<TabsInst | null>(null)
const formParams: any = reactive(
    {
        QID: null,
        courseID: route.params.courseID,
        content: '',
        tag: null,
        options: null,
        answer: null,
        title: null,
        type: 0
    }
);

const onCreateOption = () => {
    return {
        isAnswer: false,
        content: '',
    }
}

const tabKeyValue = {
    'single': 0,
    'multi': 1,
    'judge': 2,
    'blank': 3,
    'short': 4
}

const tabValueKey = {
    0: 'single',
    1: 'multi',
    2: 'judge',
    3: 'blank',
    4: 'short'
}

const tagOptions = ref();

const actionRef = ref();

const actionColumn = reactive({
    width: 25,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
        return h(TableAction, {
            style: 'button',
            actions: createActions(record),
        });
    },
});

function createActions(record) {
    return [
        {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['basic_list'],
        },
        {
            label: '修改',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
                return true;
            },
            auth: ['basic_list'],
        },
    ];
}

function addTable() {
    questionTitle.value = '添加题目';
    formParams.QID = null;
    formParams.title = null;
    formParams.content = '';
    formParams.tag = null;
    formParams.options = null;
    formParams.answer = null;
    formParams.type = 0;
    showModal.value = true;
    tabValue.value = tabValueKey[0];
    tabsInstRef.value?.syncBarPosition();
}

function handleTabUpdate(key) {
    formParams.content = '';
    formParams.tag = null;
    formParams.options = null;
    formParams.answer = null;
    formParams.type = tabKeyValue[key];
    showModal.value = true;
}

function onCheckedRow(rowKeys) {
    console.log(rowKeys);
}

const dialog = useDialog();
const handleDelete = (record) => {

    dialog.info({
        title: '提示',
        content: `您想删除这道题吗`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            //message.success('删除成功');
            deleteQuestion({ QID: record.QID, courseID: params.courseID }).then(
                () => {
                    message.success('成功');
                    reloadTable();
                }
            )
        },
        onNegativeClick: () => { },
    });
}

function readyQuill() {
    quillEditor.value.setHTML(formParams.content)
}


const handleEdit = (record) => {

    questionTitle.value = '添加题目';
    formParams.QID = record.QID;
    formParams.title = record.title;
    formParams.tag = record.tag;
    let tempArray: any = []
    for (let key in record.options) {
        console.log(record.options[key].content);
        tempArray.push(
            {
                key: record.options[key].key,
                content: record.options[key].content,
                isAnswer: record.options[key].isAnswer,
            }
        )
    }
    // console.log(tempArray);
    formParams.options = tempArray;
    if (record.type != tabKeyValue['multi']) {
        formParams.answer = record.answer[0];
    } else {
        formParams.answer = record.answer;
    }
    formParams.type = record.type;
    showModal.value = true;
    tabValue.value = tabValueKey[formParams.type];
    tabsInstRef.value?.syncBarPosition();
    formParams.content = record.content;
}

const params = reactive({
    pageSize: 10,
    courseID: route.params.courseID,
    QID: null,
    tag: null,
    type: null
});

const loadDataTable = async (res) => {
    let tagResult = await getTagList({ ...params });
    tagOptions.value = [];
    tagResult.forEach(element => {
        tagOptions.value.push(
            {
                value: element['tag'],
                label: element['tag']
            }
        )
    });
    return await getTableList({ ...params, ...res });
};

function reloadTable() {
    actionRef.value.reload();
}

const formBtnLoading = ref(false);
const showModal = ref(false);
const questionTitle = ref('');

//提交创建/修改
const message = useMessage();
const confirmForm = () => {
    let url = '';
    let params: any = formParams;
    if (params.QID) {
        url = '/teacher/teacher_question/editQuestion'
    } else {
        url = '/teacher/teacher_question/addQuestion'
    }
    if (params.type == tabKeyValue['blank'] || params.type == tabKeyValue['short']) {
        params.content = quillEditor.value.getHTML();
    }
    if (params.type == tabKeyValue['multi']) {
        if (params.options == null) {
            message.error('请添加选项');
            return;
        }
        params.answer = [];
        params.options.forEach(element => {
            if (element.isAnswer == true) {
                params.answer.push(element.key)
            }
        });
    } else {
        let tmp = params.answer;
        params.answer = [];
        params.answer.push(tmp);
    }
    http.request(
        {
            url: url,
            method: 'post',
            params: params
        }
    ).then(
        () => {
            message.success('成功');
            showModal.value = false;
            reloadTable();
        }
    );
};

const schemas: FormSchema[] = [
    {
        field: 'QID',
        component: 'NInputNumber',
        label: '题目号号',
        componentProps: {
            placeholder: '请输入题号',
            showButton: false,
            onInput: (e: any) => {
                console.log(e);
            },
        },
    },
    {
        field: 'type',
        component: 'NSelect',
        label: '类型',
        componentProps: {
            placeholder: '请选择题目类型',
            //remote:true,
            value: ref(null),
            options: [
                {
                    value: '0',
                    label: '单选',
                },
                {
                    value: '1',
                    label: '多选',
                },
                {
                    value: '2',
                    label: '判断',
                },
                {
                    value: '3',
                    label: '填空',
                }, {
                    value: '4',
                    label: '简答',
                }

            ],
        }
    },
    {
        field: 'tag',
        component: 'NSelect',
        label: '标签',
        componentProps: {
            placeholder: '请选择题目标签',
            //remote:true,
            value: ref(null),
            options: tagOptions,
        }
    }
]


const [register] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
    labelWidth: 80,
    schemas,
});

function handleSubmit(values: Recordable) {
    params['type'] = values['type'];
    params['QID'] = values['QID'];
    params['tag'] = values['tag'];
    reloadTable();
}

function handleReset(values: Recordable) {
    console.log(values);
}
</script>

<style lang="less">
.ql-toolbar.ql-snow {
    border-top: none;
    border-left: none;
    border-right: none;
    border-bottom: 1px solid #eee;
    margin-top: -10px;
}

.ql-container.ql-snow {
    border: none;
}
</style>
